package com.lc.activiti.utils.redis;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lc.activiti.config.ConstantsPile;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Set;
import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 * @author: 骆超
 * @date: 2021/5/20 16:46
 */
@Component
public class RedisUtil {

    static RedisTemplate<String, Object> redisTemplate;

    @Resource
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        RedisUtil.redisTemplate = redisTemplate;
    }

    /**
     * 获取redis中的值
     * @author 骆超
     * @date 2021/5/20
     * @param key 键
     * @return java.lang.Object
     */
    public static Object get(String key){
        try {
            return key==null?null:redisTemplate.opsForValue().get(key);
        }catch (NullPointerException e){
            return null;
        }
    }


    /**
     * 根据人员id获取缓存中的人员姓名
     * @author 骆超
     * @date 2021/6/23
     * @param userId 人员id,可以填写多个，以','分割
     * @return java.lang.String
     */
    public static String getUserName(String userId){
        JSONObject userMap = JSONUtil.parseObj(get(ConstantsPile.USER_MAP));
        StringJoiner stringJoiner = new StringJoiner(",");
        Arrays.asList(userId.split(",")).forEach(v->{
            stringJoiner.add(userMap.getStr(v));
        });
        return stringJoiner.toString();
    }

    /**
     * 将值存入redis中
     * @author 骆超
     * @date 2021/5/20
     * @param key 键
     * @param value 值
     * @return boolean
     */
    public static boolean set(String key,Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (NullPointerException e) {
            return false;
        }
    }

    /**
     * 将值存入redis中（具有时效性）
     * @author 骆超
     * @date 2021/5/20
     * @param key 键
     * @param value 值
     * @param aging 时效(分钟)
     * @return boolean
     */
    public static boolean set(String key,Object value,Integer aging) {
        try {
            redisTemplate.opsForValue().set(key, value);
            redisTemplate.expire(key,aging, TimeUnit.MINUTES);
            return true;
        } catch (NullPointerException e) {
            return false;
        }
    }


    /**
     * 清理redis中的缓存
     * @author 骆超
     * @date 2021/6/18
     */
    public static void clear() {
        Set<String> keys = redisTemplate.keys("*");
        assert keys != null;
        redisTemplate.delete(keys);
    }

    /**
     * 清理redis中指定的key
     * @author 骆超
     * @date 2021/6/18
     */
    public static void clearOfKey(String key) {
        redisTemplate.delete(key);
    }

}
